package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.HeapProblem;

import java.util.*;


/**
 * 用java的stream api耍了耍
 * <p>
 * https://stackoverflow.com/questions/29122394/word-frequency-count-java-8
 * https://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java
 * https://stackoverflow.com/questions/24010109/java-8-stream-reverse-order
 *
 * @author tzp
 * @since 2020/10/14
 */
public class LC347 implements HeapProblem {
    public int[] topKFrequent(int[] nums, int k) {
//        Map<Integer, Integer> counts = Arrays.stream(nums)
//                .boxed()
//                //.mapToObj(value -> value) //三种写法
//                //.mapToObj((IntFunction<Integer>) value -> value)
//                .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));

        HashMap<Integer, Integer> counts = new HashMap<>();
        for (int n : nums) {
            counts.compute(n, (key, oldValue) -> oldValue == null ? 1 : oldValue + 1);
        }

        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(counts.entrySet());
        list.sort((o1, o2) -> -Map.Entry.<Integer, Integer>comparingByValue().compare(o1, o2));

        return list.subList(0, k) //可以用limit()
                .stream()
                .map(Map.Entry::getKey)
                .mapToInt(x -> x)
                .toArray();
    }

    public static void main(String[] args) {
        int[] a = {1, 1, 1, 3, 3, 9};
        System.out.println(Arrays.toString(new LC347().topKFrequent(a, 2)));
    }
}
